define(['jquery', 'bootstrap', 'backend', 'form', 'table'], function ($, undefined, Backend, Form, Table) {

    var Controller = {
        index: function () {
            Table.api.init();

            //绑定事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var panel = $($(this).attr("href"));
                if (panel.length > 0) {
                    Controller.table[panel.attr("id")].call(this);
                    $(this).on('click', function (e) {
                        $($(this).attr("href")).find(".btn-refresh").trigger("click");
                    });
                }
                //移除绑定的事件
                $(this).unbind('shown.bs.tab');
            });

            //必须默认触发shown.bs.tab事件
            $('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");

            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'qingdongwms/customer/consume/index?type=0',
                    add_url: 'qingdongwms/customer/consume/add',
                    edit_url: 'qingdongwms/customer/consume/edit',
                    del_url: 'qingdongwms/customer/consume/del',
                    detail_url : 'qingdongwms/customer/consume/detail',
                    customer_url : 'qingdongwms/customer/customer/detail',
                    table: 'consume'
                }
            });

            $(document).on('click', '.show-customer', function (data) {
                var area = [$(window).width() > 1200 ? '1200px' : '95%', $(window).height() > 800 ? '800px' : '95%'];
                var options = {
                    shadeClose : false,
                    shade      : [0.3, '#393D49'],
                    area       : area,
                    callback   : function (value) {
                        //在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
                        console.log(value);
                    }
                };
                Fast.api.open($.fn.bootstrapTable.defaults.extend.customer_url + "?ids=" + $(this).data('id'), '客户详情', options);
            });

        },

        tableinfo:{
            url: '',
            pk: 'id',
            toolbar: '#toolbar',
            sortName: 'id',
            fixedRightNumber:1,
            fixedColumns:true,
            columns: [
                [
                    {field: 'state', checkbox: true},
                    {field: 'number', title: __('报销单号'), operate:false, formatter : function (value, row, index) {

                            return "<a href='javascript:void(0);' class='btn-dialog'  data-shade=\"0.3\"\n" +
                                "data-url=\""+ $.fn.bootstrapTable.defaults.extend.detail_url + "?ids=" + row.id+
                                "\" data-title=\"费用详情\" ' >" + value + "</a>";
                        }},
                    {field: 'submit_date', title: __('消费日期'), operate: '=', addclass: 'datetimepicker',data:"data-date-format=\" YYYY-MM-DD\""},

                    {field: 'customer', title: __('关联客户'), operate:false, formatter : function (value, row, index) {
                            if(row.customer){
                                return "<a href='javascript:void(0);' data-id='" + row.customer.id + "' class='show-customer'>" + row.customer.name + "</a>";
                            }else{
                                return '';
                            }
                        }},
                    {field : 'customer_id', title : '关联客户', visible: false, addClass: "selectpage", extend: "data-source='qingdongwms/customer/customer/index' data-field='name'"},

                    {field: 'money', title: __('消费金额')},
                    {field: 'check_status', title: __('审批状态'), formatter: Table.api.formatter.status,  searchList: {0: __('待审核'), 1: __('审核中'), 2: __('审核通过'), 3: __('审核拒绝'), 4: __('撤销'), 5: __('草稿')},custom: {0: 'gray', 1: 'gray',2: 'success', 3: 'danger', 4: 'danger', 5: 'danger'}},
                    {field: 'remark', title: __('备注')},

                    {field: 'staff.name', title: __('创建人'),operate:false},
                    {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},

                ]
            ],
            //启用普通表单搜索
            search:false,
            commonSearch: true,
            searchFormVisible: true,
        },
        table: {
            first: function () {
                var table = $("#table");

                Controller.tableinfo.url=location.href+'&type=0';
                Controller.tableinfo.toolbar='#toolbar';
                Controller.tableinfo.columns[0][Controller.tableinfo.columns[0].length-1].table=table;

                // 初始化表格
                table.bootstrapTable(Controller.tableinfo);

                // 为表格绑定事件
                Table.api.bindevent(table);
            },
            second: function () {
                // 初始化表格参数配置
                Table.api.init({});

                var table = $("#table1");

                Controller.tableinfo.url=location.href+'&type=1';
                Controller.tableinfo.toolbar='#toolbar1';
                Controller.tableinfo.columns[0][Controller.tableinfo.columns[0].length-1].table=table;

                // 初始化表格
                table.bootstrapTable(Controller.tableinfo);
                // 为表格绑定事件
                Table.api.bindevent(table);
            },
            third: function () {
                // 初始化表格参数配置
                Table.api.init({});

                var table = $("#table2");

                Controller.tableinfo.url=location.href+'&type=2';
                Controller.tableinfo.toolbar='#toolbar2';
                Controller.tableinfo.columns[0][Controller.tableinfo.columns[0].length-1].table=table;

                // 初始化表格
                table.bootstrapTable(Controller.tableinfo);
                // 为表格绑定事件
                Table.api.bindevent(table);
            },
        },
        add    : function () {

            Controller.api.bindevent();
        },
        clf: function () {
            $(document).on('click', '.btn-success', function () {
                var param = {};
                param.car_number = $('input[name="row[car_number]"]').val(),
                    param.consume_date = $('input[name="row[consume_date]"]').val(),
                    param.start_mileage = $('input[name="row[start_mileage]"]').val(),
                    param.end_mileage = $('input[name="row[end_mileage]"]').val(),
                    param.mileage = $('input[name="row[mileage]"]').val(),
                    param.consume_money = $('input[name="row[consume_money]"]').val(),
                    param.file_ids = $('input[name="row[file_ids]"]').val(),
                    param.remark = $('textarea[name="row[remark]"]').val();
                Fast.api.close({'params': param})
            }).on('change', '.miles-calcute', function () {
                var start_mileage = $('input[name="row[start_mileage]"]').val(),
                    end_mileage = $('input[name="row[end_mileage]"]').val();
                if (start_mileage && end_mileage) {
                    var number = parseInt(end_mileage) - parseInt(start_mileage);
                    $('input[name="row[mileage]"]').val(number);
                    var curl = "qingdongwms/customer/consume/consume_count";
                    $.ajax({
                        url: curl,
                        type: 'post',
                        dataType: 'json',
                        data: {number:number},
                        success: function (result) {
                            $('input[name="row[consume_money]"]').val(result.data.money);
                        }
                    });
                }
            })
            Controller.api.bindevent();
        },
        other: function () {
            $(document).on('click', '.btn-success', function () {
                var param = {};
                param.consume_date = $('input[name="row[consume_date]"]').val(),
                    param.consume_money = $('input[name="row[consume_money]"]').val(),
                    param.file_ids = $('input[name="row[file_ids]"]').val(),
                    param.remark = $('textarea[name="row[remark]"]').val();
                Fast.api.close({'params': param})
            })
            Controller.api.bindevent();
        },
        edit    : function () {
            Controller.api.bindevent();
        },
        detail : function () {
            $('.stafflist').popover({
                placement : 'bottom',
                trigger : 'hover'
            });
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                var num = 0;
                $(document).on("change", "#consume-type", function () {
                    var type = $("#consume-type option:selected").val();
                    var money=$('#c-money').val();
                    money=parseFloat(money)
                    if(!money){
                        money=0;
                    }
                    var area = [$(window).width() > 1200 ? '1200px' : '95%', $(window).height() > 800 ? '800px' : '95%'];
                    var options;
                    if (type == '交通费') {
                        options = {
                            shadeClose: false,
                            shade: [0.3, '#393D49'],
                            area: area,
                            callback: function (value) {
                                //在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
                                var params = value.params;
                                money+=parseFloat(params.consume_money);
                                var clf_content = '<div class="content-list">' +
                                    '<div class="form-group" >\n' +
                                    '<div class="alert alert-warning-light no-margin">交通费<span class="btn btn-sm btn-danger btn-remove" style="float:right;"><i class="fa fa-times"></i></span></div>\n' +
                                    '<input type="hidden" name="row[detail][' + num + '][consume_type]" class="form-control" value = "交通费"/>\n' +
                                    '</div>\n' +

                                    '<div class="form-group" >\n' +
                                    '<label class="control-label col-xs-6 col-sm-2">车牌号:</label>\n' +
                                    '<div class="col-xs-6 col-sm-4">\n' +
                                    '<input type="text" name="row[detail][' + num + '][car_number]" placeholder="请输入车牌号" class="form-control" value = "' + params.car_number + '"/>\n' +
                                    '</div>\n' +

                                    '<label class="control-label col-xs-6 col-sm-2">发生时间:</label>\n' +
                                    '<div class="col-xs-6 col-sm-4">\n' +
                                    '<input name="row[detail][' + num + '][consume_date]" type="text" placeholder="请选择发生时间" class="form-control datetimepicker" value = "' + params.consume_date + '"   data-date-format="YYYY-MM-DD">\n' +
                                    '</div>\n' +
                                    '</div>\n' +
                                    '<div class="form-group" >\n' +
                                    '<label class="control-label col-xs-6 col-sm-2">金额:</label>' +
                                    '<div class="col-xs-6 col-sm-4">' +
                                    '<input type="number" name="row[detail][' + num + '][consume_money]" placeholder="请输入金额" class="form-control"  value = "' + params.consume_money + '"  data-rule="required"/>' +
                                    '</div>' +


                                    '<label class="control-label col-xs-6 col-sm-2">起始公里数:</label>\n' +
                                    '<div class="col-xs-6 col-sm-4">\n' +
                                    '<input type="text" name="row[detail][' + num + '][start_mileage]" placeholder="请输入起始公里数" class="form-control"  value = "' + params.start_mileage + '"/>\n' +
                                    '</div>\n' +

                                    '</div>\n' +

                                    '<div class="form-group" >\n' +
                                    '<label class="control-label col-xs-6 col-sm-2">结束公里数:</label>\n' +
                                    '<div class="col-xs-6 col-sm-4">\n' +
                                    '<input name="row[detail][' + num + '][end_mileage]" type="text" placeholder="请输入结束公里数" class="form-control" value = "' + params.end_mileage + '" >\n' +
                                    '</div>\n' +
                                    '<label class="control-label col-xs-6 col-sm-2">公里数:</label>' +
                                    '<div class="col-xs-6 col-sm-4">' +
                                    '<input type="number" name="row[detail][' + num + '][mileage]" placeholder="请输入公里数" class="form-control"  value = "' + params.mileage + '"  data-rule="required"/>' +
                                    '</div>' +
                                    '</div>\n' +

                                    '<div class="form-group">' +
                                    '<label class="control-label col-xs-6 col-sm-2">消费凭证:</label>' ;
                                clf_content+= '<div class="col-xs-6 col-sm-10"><div class="input-group">' +
                                    '<input id="c-image-'+num+'" class="form-control" size="35" ' +
                                    'placeholder="请上传消费凭证" name="row[detail][' + num + '][file_ids]"' +
                                    'type="text"  value = "' + params.file_ids + '" >' +
                                    '<div class="input-group-addon no-border no-padding">' +
                                    '<span><button type="button" class="btn btn-danger faupload"' +
                                    'data-url="ajax/upload?type=7" data-input-id="c-image-'+num+'"' +
                                    'data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp"' +
                                    'data-multiple="false" data-preview-id="p-image-'+num+'">' +
                                    '<i class="fa fa-upload"></i>上传</button></span> </div>' +
                                    '<span class="msg-box n-right"></span></div><ul class="row list-inline faupload-preview" id="p-image-'+num+'"></ul></div></div>';

                                clf_content+= '<div class="form-group"><label class="control-label col-xs-6 col-sm-2">备注:</label>' +
                                    '<div class="col-xs-6 col-sm-6">' +
                                    '<textarea name="row[detail][' + num + '][remark]"  class="form-control" rows="2" placeholder="请填写备注">' + params.remark + '</textarea>' +
                                    '</div></div>' +
                                    '</div>';
                                $('#consume-content').append(clf_content);
                                Form.events.datetimepicker($("form"));
                                Form.events.plupload($("form"));

                                $('#c-money').val(money);
                            }

                        };
                        Fast.api.open('qingdongwms/customer/consume/clf', type, options);
                    } else {
                        options = {
                            shadeClose: false,
                            shade: [0.3, '#393D49'],
                            area: area,
                            callback: function (value) {
                                //在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
                                var params = value.params;
                                money+=parseFloat(params.consume_money);
                                var clf_content = '<div class="content-list">' +
                                    '<div class="form-group" >\n' +
                                    '<div class="alert alert-warning-light no-margin">' + type + '<span class="btn btn-sm btn-danger btn-remove" style="float:right;"><i class="fa fa-times"></i></span></div>\n' +
                                    '<input type="hidden" name="row[detail][' + num + '][consume_type]" class="form-control consume_type" value = "' + type + '" />\n' + '' +
                                    '</div>\n' +
                                    '<div class="form-group" >\n' +
                                    '<label class="control-label col-xs-6 col-sm-2">发生日期:</label>\n' +
                                    '<div class="col-xs-6 col-sm-4">\n' +
                                    '<input name="row[detail][' + num + '][consume_date]" type="text" placeholder="请选择发生日期" class="form-control datetimepicker" value = "' + params.consume_date + '"   data-date-format="YYYY-MM-DD">\n' +
                                    '</div>\n' +
                                    '<label class="control-label col-xs-6 col-sm-2">金额:</label>' +
                                    '<div class="col-xs-6 col-sm-4">' +
                                    '<input type="number" name="row[detail][' + num + '][consume_money]" placeholder="请输入金额" class="form-control"  value = "' + params.consume_money + '"  data-rule="required"/>' +
                                    '</div>' +
                                    '</div>\n' +
                                    '<div class="form-group">' +
                                    '<label class="control-label col-xs-6 col-sm-2">消费凭证:</label>' +
                                    '<div class="col-xs-6 col-sm-10">' ;
                                clf_content+= ' <div class="input-group">' +
                                    '<input id="c-image-'+num+'" class="form-control" placeholder="请上传消费凭证" size="35" ' +
                                    'name="row[detail][' + num + '][file_ids]"' +
                                    'type="text"  value = "' + params.file_ids + '" >' +
                                    '<div class="input-group-addon no-border no-padding">' +
                                    '<span><button type="button" class="btn btn-danger faupload"' +
                                    'data-url="ajax/upload?type=7" data-input-id="c-image-'+num+'"' +
                                    'data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp"' +
                                    'data-multiple="false" data-preview-id="p-image-'+num+'">' +
                                    '<i class="fa fa-upload"></i>上传</button></span> </div>' +
                                    '<span class="msg-box n-right"></span></div><ul class="row list-inline faupload-preview" id="p-image-'+num+'"></ul>';
                                clf_content+= '</div></div><div class="form-group">' +
                                    '<label class="control-label col-xs-6 col-sm-2">备注:</label>' +
                                    '<div class="col-xs-6 col-sm-6">' +
                                    '<textarea name="row[detail][' + num + '][remark]"  class="form-control" rows="2" placeholder="请填写备注">' + params.remark + '</textarea>' +
                                    '</div>' +
                                    '</div></div>';
                                $('#consume-content').append(clf_content);

                                Form.events.datetimepicker($("form"));
                                Form.events.plupload($("form"));
                                console.log(money)
                                $('#c-money').val(money);
                            }
                        };
                        Fast.api.open('qingdongwms/customer/consume/other', type, options);
                    }
                    num = num + 1;
                    $("#consume-type").val(0)
                }).on('click', '.btn-remove', function () {
                    $(this).parents('.content-list').remove();
                });

                $(document).on("click", ".select-customer", function(){
                    var $this=$(this);
                    top.Fast.api.open($(this).data("url") , __('Select'), {callback: function (data) {
                            $this.html(data.name);
                            $('[name="'+$this.data('name')+'"]').val(data.id);
                        },area:["100%", "100%"]});
                })

                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {}
        },

    };
    return Controller;
});